const backgroundImages = [
    '../assets/images/index_bg.jpg',
    '../assets/images/index_bg1.jpg'
];

// 更新时间函数
function updateTime() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    document.getElementById('time-display').textContent = `${hours}:${minutes}:${seconds}`;
}

// 更新农历日期
function updateLunarDate() {
    const now = new Date();
    const lunarDate = getFullLunarDate(now);
    document.getElementById('lunar-date').textContent = lunarDate;
}

// 字体加载状态管理
function loadFonts() {
    const fontNames = [
        'KuangPaiShouShu',
        'FZZhuZiAYuanJianB'
    ];

    let loadedCount = 0;
    const totalFonts = fontNames.length;

    fontNames.forEach(fontName => {
        if (document.fonts.check(`1em ${fontName}`)) {
            loadedCount++;
            if (loadedCount === totalFonts) {
                document.documentElement.classList.add('fonts-loaded');
            }
            return;
        }

        document.fonts.load(`1em ${fontName}`).then(() => {
            loadedCount++;
            if (loadedCount === totalFonts) {
                document.documentElement.classList.add('fonts-loaded');
            }
        }).catch(e => {
            console.error(`字体 ${fontName} 加载失败:`, e);
            loadedCount++;
            if (loadedCount === totalFonts) {
                document.documentElement.classList.add('fonts-loaded');
            }
        });
    });

    if (loadedCount === totalFonts) {
        document.documentElement.classList.add('fonts-loaded');
    }
}

function getRandomIndex() {
    const lastIndex = parseInt(sessionStorage.getItem('lastBgIndex')) || -1;
    let newIndex;

    do {
        newIndex = Math.floor(Math.random() * backgroundImages.length);
    } while (backgroundImages.length > 1 && newIndex === lastIndex);

    return newIndex;
}

// 动态调整中文引语字体大小（带最大字体限制）
function adjustQuoteFontSize() {
    const quoteElement = document.querySelector('.chinese-quote');
    const container = quoteElement.parentElement;

    // 获取容器宽度（可用宽度的90%）
    const containerWidth = container.offsetWidth * 0.9;
    const text = quoteElement.textContent;

    // 创建临时测量元素
    const measurer = document.createElement('div');
    measurer.style.position = 'absolute';
    measurer.style.left = '-9999px';
    measurer.style.whiteSpace = 'nowrap';
    measurer.style.fontFamily = getComputedStyle(quoteElement).fontFamily;
    measurer.style.fontWeight = getComputedStyle(quoteElement).fontWeight;
    measurer.style.visibility = 'hidden';
    measurer.textContent = text;
    document.body.appendChild(measurer);

    // 设置初始字体大小
    let fontSize = 100; // 从100px开始测试
    measurer.style.fontSize = `${fontSize}px`;

    // 计算文本宽度
    const textWidth = measurer.offsetWidth;

    // 计算最佳字体大小
    const scaleFactor = containerWidth / textWidth;
    let bestSize = Math.floor(fontSize * scaleFactor * 0.95); // 留5%边距

    // 设置最大字体限制（根据窗口宽度动态调整）
    const maxSize = Math.min(
        150, // 绝对最大值
        window.innerWidth * 0.08, // 基于窗口宽度的相对最大值
        window.innerHeight * 0.1  // 基于窗口高度的相对最大值
    );

    // 应用最佳大小（考虑最小值和最大值）
    bestSize = Math.min(Math.max(24, bestSize), maxSize);
    quoteElement.style.fontSize = `${bestSize}px`;

    // 清理临时元素
    document.body.removeChild(measurer);
}

// 防抖函数优化性能
function debounce(func, wait = 100) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(context, args);
        }, wait);
    };
}

document.addEventListener('DOMContentLoaded', () => {
    loadFonts();

    // 初始化时间和农历日期
    updateTime();
    updateLunarDate();

    // 每秒更新时间
    setInterval(() => {
        updateTime();
        updateLunarDate();
    }, 1000);

    const randomIndex = getRandomIndex();
    const selectedImage = backgroundImages[randomIndex];

    const bgImg = new Image();
    bgImg.src = selectedImage;

    const textureImg = new Image();
    textureImg.src = '../assets/images/980.jpg';

    bgImg.onload = () => {
        document.body.style.backgroundImage = `url('${selectedImage}')`;
        document.body.style.opacity = 0;

        setTimeout(() => {
            document.body.style.transition = 'opacity 1s ease-in';
            document.body.style.opacity = 1;
        }, 100);

        sessionStorage.setItem('lastBgIndex', randomIndex);
    };

    // 在字体加载完成后调整引语大小
    const checkFontsLoaded = setInterval(() => {
        if (document.documentElement.classList.contains('fonts-loaded')) {
            clearInterval(checkFontsLoaded);
            adjustQuoteFontSize();
        }
    }, 100);

    // 窗口大小变化时重新计算（使用防抖优化）
    const debouncedAdjust = debounce(adjustQuoteFontSize, 150);
    window.addEventListener('resize', debouncedAdjust);

    setTimeout(() => {
        if (!document.documentElement.classList.contains('fonts-loaded')) {
            console.warn('字体加载超时，使用回退方案');
            document.documentElement.classList.add('fonts-loaded');
            adjustQuoteFontSize();
        }
    }, 3000);
});